Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Inheritance → Method Overriding

Inheritance

Method Overriding

Method Overriding in Python

Method overriding is a powerful feature in object-oriented programming (OOP) that allows a subclass to provide a specific implementation for a method that is already defined in its superclass (parent class). This enables polymorphism, where objects of different classes can respond to the same method call in their own specific ways. In Python, this is achieved without explicit keywords like `override` (unlike some languages like Java). Instead, it relies on the method resolution order (MRO).

Core Principles

Inheritance: Overriding requires inheritance. A subclass must inherit from a superclass. Method Signature Matching: The overriding method in the subclass must have the exact same name and signature (number and types of parameters) as the method in the superclass. If the signatures differ, it's not overriding, but rather method overloading (which Python doesn't directly support in the same way as some other languages). Dynamic Dispatch: At runtime, Python determines which version of the method to call based on the object's type. This is called dynamic dispatch or runtime polymorphism. Example 1: Simple Overriding
Python simple overriding example class Animal: def speak(self): print("Generic animal sound") class Dog(Animal): def speak(self): print("Woof!") class Cat(Animal): def speak(self): print("Meow!") animals = [Animal(), Dog(), Cat()] for animal in animals: animal.speak() # Polymorphic behavior: each animal speaks differently

Output

Generic animal sound Woof! Meow!
Here, `Dog` and `Cat` override the `speak` method inherited from `Animal`. Each class provides its own implementation.
Example 2: Overriding with Parameters
Overriding with Parameters class Shape: def area(self, length, width): return length * width class Rectangle(Shape): def area(self, length, width): return length * width class Square(Shape): def area(self, side): #This will not override, as signature is different return side * side rect = Rectangle() print(f"Rectangle area: {rect.area(5, 10)}") sq = Square() print(f"Square area: {sq.area(5,5)}")
In this example, `Rectangle` correctly overrides `area`. `Square` does not override, because it changes the parameter signature. Calling `sq.area(5)` will result in a TypeError because `Square` has only one argument. To fix it, we would do:
Working example class Square(Shape): def area(self, length, width): #Correct signature, overriding the method. return length * width

Output

Rectangle area: 50 Square area: 25

Example 3: Overriding and Calling the Superclass Method Sometimes, you want to extend the superclass's method rather than completely replacing it. You can call the superclass's method using `super()`.
Overriding and Calling the Superclass Method class Bird: def fly(self): print("Bird is flapping its wings.") class Penguin(Bird): def fly(self): print("Penguin cannot fly but...") super().fly() #Calls Bird's fly method p = Penguin() p.fly()

Output

Penguin cannot fly but... Bird is flapping its wings.
`Penguin` overrides `fly`, but also calls the `fly` method from the `Bird` class using `super().fly()`.
Example 4: Method Resolution Order (MRO) Understanding MRO is crucial when dealing with multiple inheritance. Python uses C3 linearization to determine the order in which methods are searched.
Method Resolution Order (MRO) class A: def method(self): print("A's method") class B(A): def method(self): print("B's method") class C(A): def method(self): print("C's method") class D(B, C): pass d = D() d.method() print(D.__mro__) # Shows the Method Resolution Order

Output

B's method (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
The output shows the MRO, clarifying the order in which Python searches for methods. In this case, `B`'s `method` overrides `A`'s, and because `D` inherits from `B` before `C`, `B`'s version takes precedence.
In summary, method overriding is a fundamental aspect of OOP in Python, allowing for flexible and reusable code through polymorphism. Understanding the rules of overriding and MRO is essential for writing robust and maintainable object-oriented programs. Remember to always match method signatures when intending to override a superclass method. Using `super()` enables elegant extension of superclass functionality within overridden methods.

Tutorials